import { ref } from 'vue'
import { defineStore } from 'pinia'
import { loginAPI, LoginParams, LoginResult } from '@/axios/api/login/login'
import { constantRoute, asyncRouter, anyRoute } from '@/route/routes'
import router from '@/route/index'
//@ts-ignore
import cloneDeep from 'lodash/cloneDeep'
//@ts-ignore
import CryptoJS from 'crypto-js'

import { setToken_local, getToken_local, setToken_session, getToken_session } from '@/utils/token'

import LocalForageInstance from '@/utils/localforage';


const db = LocalForageInstance.getInstance();

// 定义一个密钥
const SECRET_KEY = 'your-secret-key'

// 加密函数
function encrypt(data: any) {
    return CryptoJS.AES.encrypt(JSON.stringify(data), SECRET_KEY).toString()
}

// 解密函数
function decrypt(data: any) {
    const bytes = CryptoJS.AES.decrypt(data, SECRET_KEY)
    return JSON.parse(bytes.toString(CryptoJS.enc.Utf8))
}

const useUserStore = defineStore('user', () => {
    let username = ref()
    let access_token = ref(getToken_session('access_token') || '')
    let refresh_token = ref(getToken_local('refresh_token') || '')
    let userr_all_routes = ref<any[]>(constantRoute)
    let buttons = ref<any[]>([])
    let UserNumber=''

    function filterAsyncRoutes(arouter: any, backRoutes: any) {
        return arouter.filter((item: any) => {
            if (backRoutes.includes(item.name)) {
                if (item.children && item.children.length > 0) {
                    item.children = filterAsyncRoutes(item.children, backRoutes)
                }
                return true
            }
        })
    }

    function resetRouter(userinfo: any) {
        userinfo.forEach((item: any) => {
            router.addRoute(item)
        })
    }
    // 登录接口
    const userlogin = async (userList: LoginParams) => {
        try {
            let res: LoginResult = await loginAPI(userList)
            access_token.value = res.data.access_token;
            refresh_token.value = res.data.refresh_token;
            username.value = res.data.username;
            setToken_session('access_token', res.data.access_token);
            setToken_local('refresh_token', res.data.refresh_token);
            buttons.value = res.data.buttons;
            db.setdb('username', res.data.username);
            db.setdb('buttons', encrypt(res.data.buttons));
            db.setdb('routes', encrypt(res.data.routes));
            // 过滤异步路由
            let filterRoutes = filterAsyncRoutes(cloneDeep(asyncRouter), res.data.routes);
            userr_all_routes.value = [...constantRoute, ...filterRoutes, anyRoute];
            resetRouter([...filterRoutes, anyRoute]); // 重置路由
            return 'ok';
        } catch (error: any) {
            return Promise.reject(new Error(error.msg||'登录失败'));
        }
    }

    // 退出登录
    const userlogout = async function () {
        access_token.value = '';
        refresh_token.value = '';
        sessionStorage.removeItem('access_token');
        localStorage.removeItem('refresh_token');
        userr_all_routes.value = [];
        username.value = '';
        return Promise.all([
            db.remove('username'),
            db.remove('buttons'),
            db.remove('routes')
        ]).then(() => {
            window.location.href = '/login';
            return 'ok';
        }).catch((error) => {
            throw new Error('退出失败: ' + error);
        });
    }

    return {

        userlogin,
        access_token,
        refresh_token,
        userr_all_routes,
        resetRouter,
        filterAsyncRoutes,
        encrypt,
        decrypt,
        username,
        userlogout,
        buttons,
        UserNumber
    }
})

export default useUserStore
